package com.qf.air.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.air.entity.Air;
import com.qf.air.enums.AirEnum;
import com.qf.air.exception.AirEx;
import com.qf.air.mapper.AirMapper;
import com.qf.air.service.AirService;
import com.qf.air.service.DistrictService;
import com.qf.air.util.R;
import com.qf.air.vo.ResultVO;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: 维多利加
 * @Date: 2021/3/20 11:02
 */
@Service
public class AirServiceImpl implements AirService {

    @Autowired
    private AirMapper airMapper;

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private DistrictService districtService;

    @Override
    public ResultVO findByPageAndDistrictId(Integer page, Integer rows, Integer districtId, String monitoringStation, Date startTime, Date endTime) throws IOException {
        /**
         * 去数据库查询空气质量信息
        PageHelper.startPage(page, rows);

        List<Air> all = airMapper.findByDistrictId(districtId, monitoringStation, startTime, endTime);

        PageInfo<Air> pageInfo = new PageInfo<>(all);

        return pageInfo;*/

        //1. 创建SearchRequest
        SearchRequest searchRequest = new SearchRequest();

        //2. 封装数据
        //2.1 索引名称
        searchRequest.indices("air");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //2.2 查询条件(BoolQuery)
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //2.2.1 districtId区域id
        if(districtId != null && districtId != 0){
            boolQuery.must(QueryBuilders.termQuery("districtId",districtId));
        }
        //2.2.2 monitoringStation监测站名称
        if(!StringUtils.isEmpty(monitoringStation)){
            boolQuery.must(QueryBuilders.matchQuery("monitoringStation",monitoringStation));
        }

        //2.2.3 startTime开始时间
        if(startTime != null){
            String startTimeFormat = new SimpleDateFormat("yyyy-MM-dd").format(startTime);
            boolQuery.must(QueryBuilders.rangeQuery("monitorTime").gte(startTimeFormat));
        }

        //2.2.4 endTime结束时间
        if(endTime != null){
            String endTimeFormat = new SimpleDateFormat("yyyy-MM-dd").format(endTime);
            boolQuery.must(QueryBuilders.rangeQuery("monitorTime").lte(endTimeFormat));
        }
        // 2.2.5 封装到sourceBuilder
        sourceBuilder.query(boolQuery);

        //2.3 分页信息
        sourceBuilder.from((page - 1) * rows);
        sourceBuilder.size(rows);

        //2.4 高亮查询
        if(!StringUtils.isEmpty(monitoringStation)) {
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("monitoringStation");
            highlightBuilder.preTags("<span style='color:red;'>");
            highlightBuilder.postTags("</span>");
            highlightBuilder.fragmentSize(99999);
            sourceBuilder.highlighter(highlightBuilder);
        }

        //2.5 封装到request中
        searchRequest.source(sourceBuilder);

        //3. 发送请求,获取Response
        SearchResponse resp = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        //4. 通过Response解析数据封装为ResultVO
        ResultVO vo = R.ok();
        //4.1 封装数据的总条数
        vo.setCount(resp.getHits().getTotalHits().value);
        
        //4.2 封装具体的数据
        List<Map> data = new ArrayList<>();
        SearchHit[] hits = resp.getHits().getHits();
        for (SearchHit hit : hits) {
            Map<String, Object> map = hit.getSourceAsMap();
            data.add(map);
        }
        if(!StringUtils.isEmpty(monitoringStation)){
            // 说明有高亮显示
            for (int i = 0; i < hits.length; i++) {
                HighlightField monitoringStationHighlight = hits[i].getHighlightFields().get("monitoringStation");
                String highLight = monitoringStationHighlight.fragments()[0].toString();
                data.get(i).put("monitoringStation",highLight);
            }
        }
        vo.setData(data);
        //5. 返回
        return vo;
    }

    @Override
    @Transactional
    public void save(Air air) throws IOException {
        air.setLastModifyTime(new Date());
        Integer count = airMapper.save(air);
        if (count != 1) {
            //添加失败，记录日志，抛出异常
            System.out.println("添加信息失败！ air=" + air);
            throw new AirEx(AirEnum.AIR_ADD_ERROR);
        }
        //封装数据
        // 主键id (主键回填)
        // 检测区域名称 (DistrictService)
        air.setDistrictName(districtService.findDistrictNameById(air.getDistrictId()));
        // 最后修改时间 (添加数据库之前,设置好)

        // 添加数据到Elasticsearch
        IndexRequest indexRequest = new IndexRequest();
        indexRequest.index("air");
        indexRequest.id(air.getId() + "");
        indexRequest.source(new ObjectMapper().convertValue(air,Map.class));
        IndexResponse resp = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
        if(!resp.getResult().toString().equalsIgnoreCase("CREATED")){
            System.out.println("添加信息失败！ air=" + air);
            throw new AirEx(AirEnum.AIR_ADD_ERROR);
        }

    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = -1, readOnly = false, rollbackFor = Exception.class, noRollbackFor = ArithmeticException.class)
    public void deleteById(Integer id) {
        int i = airMapper.deleteById(id);

        if (i != 1) {
            System.out.println("删除失败！ id=" + id);
            throw new AirEx(AirEnum.AIR_DELETE_ERROR);
        }

    }

    @Override
    @Transactional
    public void updateById(Air air) {
        int count = airMapper.updateById(air);

        if (count != 1) {
            System.out.println("修改失败！ air=" + air);
            throw new AirEx(AirEnum.AIR_UPDATE_ERROR);
        }
    }

    @Override
    public ResultVO findDistrictAirQualityCount() throws IOException {
        //1. SearchRequest
        SearchRequest request = new SearchRequest();

        //2. set Data,封装Request
        request.indices("air");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.aggregation(AggregationBuilders.terms("airCount").field("districtName").size(5));
        request.source(sourceBuilder);
        //3. send Request,获取Response
        SearchResponse resp = restHighLevelClient.search(request, RequestOptions.DEFAULT);

        //4. 封装数据
        ResultVO vo = R.ok();
        Terms provinceCount = resp.getAggregations().get("airCount");
        List<Map> data = new ArrayList<>();
        for (Terms.Bucket bucket : provinceCount.getBuckets()) {
            Map map = new HashMap();
            map.put("key",bucket.getKey() + "");
            map.put("docCount",bucket.getDocCount());
            data.add(map);
        }
        vo.setData(data);
        return vo;
    }
}
